<template>
  <el-dialog
    :before-close="handleClose"
    :model-value="visible"
    :title="$t('formgen.rateText.title')"
    width="500px"
    @update:model-value="handleVisibleChange"
  >
    <div class="mb10">{{ $t("formgen.rateText.fillTip") }}</div>
    <div class="text-list">
      <div
        v-for="(text, index) in tempTexts"
        :key="index"
        class="custom-text-item"
      >
        <el-input
          v-model="tempTexts[index]"
          :placeholder="`${index + 1}${$t('formgen.rateText.scoreText')}`"
          size="default"
        >
          <template #prepend>{{ index + 1 }}{{ $t("formgen.rateText.score") }}</template>
        </el-input>
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">
          {{ $t("common.cancel") }}
        </el-button>
        <el-button
          type="primary"
          @click="handleConfirm"
        >
          {{ $t("common.enter") }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { defineProps, defineEmits, ref, watch } from "vue";

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  activeData: {
    type: Object,
    required: true
  }
});

const emit = defineEmits(["update:visible", "update:texts"]);

const tempTexts = ref([]);
const defaultTexts = ["非常糟糕", "失望", "一般", "满意", "惊喜"];

const handleVisibleChange = val => {
  emit("update:visible", val);
};

// 监听对话框显示状态，初始化数据
watch(
  () => props.visible,
  newVal => {
    if (newVal) {
      initTempTexts();
    }
  }
);

// 初始化临时文案数组
const initTempTexts = () => {
  const max = props.activeData.max || 5;
  tempTexts.value = new Array(max).fill("").map((_, index) => {
    return props.activeData.texts?.[index] || (index < defaultTexts.length ? defaultTexts[index] : "");
  });
};

const handleClose = () => {
  emit("update:visible", false);
};

const handleConfirm = () => {
  // 生成新的 textMap
  const textMap = {};
  tempTexts.value.forEach((text, index) => {
    if (text) {
      textMap[index + 1] = text;
    }
  });

  // 生成完整的 texts 数组
  const max = props.activeData.max || 5;
  const texts = new Array(max).fill("");
  const scores = Object.keys(textMap)
    .map(Number)
    .sort((a, b) => a - b);
  // 填充文案
  let lastText = "";
  scores.forEach((score, index) => {
    const currentText = textMap[score];
    if (currentText) {
      lastText = currentText;
      const nextScore = scores[index + 1] || max + 1;
      for (let i = score - 1; i < nextScore - 1; i++) {
        texts[i] = currentText;
      }
    }
  });

  emit("update:texts", { texts, textMap });
  handleClose();
};
</script>

<style scoped>
.text-list {
  max-height: 60vh;
  overflow-y: auto;
  padding: 0 10px;
}

.custom-text-item {
  margin-bottom: 12px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
